<template>
  <div
    class="ScaleBox"
    ref="ScaleBoxRef"
    :style="{
      width: width + 'px',
      height: height + 'px'
    }"
  >
    <slot></slot>
  </div>
</template>

<script>
export default {
  name: 'ScaleScreen',
}
</script>

<script setup>
import { onMounted, ref } from 'vue';

const scale = ref(0);
const width = ref(1920);
const height = ref(1080);
const ScaleBoxRef = ref();

function getScale() {
  // 固定好16：9的宽高比，计算出最合适的缩放比
  const wh = window.innerHeight / height.value;
  const ww = window.innerWidth / width.value;
  console.log(ww < wh ? ww : wh);
  return wh;
}

function setScale() {
  // 获取到缩放比例，设置它
  scale.value = getScale();
  if (ScaleBoxRef.value) {
    ScaleBoxRef.value.style.setProperty('--scale', scale.value);
  }
}

function debounce(fn, delay) {
  const delays = delay || 500;
  let timer;
  return function () {
    const th = this;
    const args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function () {
      timer = null;
      fn.apply(th, args);
    }, delays);
  };
}

onMounted(() => {
  setScale();
  window.addEventListener('resize', debounce(setScale));
});
</script>

<style lang="less">
  #ScaleBox {
    --scale: 1;
  }
  .ScaleBox {
    position: relative;
    transform: scale(var(--scale)) translate(-50%, 0%);
    display: flex;
    flex-direction: column;
    left: 50%;
    top: 0%;
    transition: 0.3s;
    z-index: 999;
    transform-origin: 0 0;
  }
</style>
